package org.seefly.iprint.controller;

import org.seefly.iprint.entity.*;
import org.seefly.iprint.service.AdminService;
import org.seefly.iprint.service.OrderService;
import org.seefly.iprint.utils.IPUtils;
import org.seefly.iprint.vo.LoginUserVo;
import org.seefly.iprint.vo.OrderQueryVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminOrderController {

    private AdminService service;
    private OrderService orderService;

    public AdminOrderController(AdminService service,OrderService orderService) {
        this.service = service;
        this.orderService = orderService;
    }

    @Value("${user.login.success}")
    /**登陆成功*/
    private String loginSuccess;
    /**账号或密码错误*/
    @Value("${user.login.accountOrPwdError}")
    private String accountOrPwdError;
    /**验证码错误*/
    @Value("${user.login.codeError}")
    private String codeError;
    /**layui数据表格状态码*/
    @Value("${layui.status.success}")
    private String lauiTableStatus;
    /**未付款*/
    @Value("${orders.status.unpaid}")
    private String unpaid;
    /**已付款，未打印状态*/
    @Value("${orders.status.paid}")
    private String paid;
    /**已付款，已打印*/
    @Value("${orders.status.printed}")
    private String printed;
    /**已成功*/
    @Value("${orders.status.success}")
    private String success;

    
    /**
     * @Description (登陆校验)
     * @param vo
     * @param session
     * @param request
     * @return 异步响应登陆信息 验证码错误、账号密码错误、登陆成功
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public String adminDoLogin(@RequestBody LoginUserVo vo, HttpSession session, HttpServletRequest request) {
        String loginCode = (String) session.getAttribute("loginCode");
        String msg = null;
        // 判断验证码
        if (loginCode != null && loginCode.equalsIgnoreCase(vo.getCode())) {
            //获取真实IP
            vo.setLoginIP(IPUtils.getIP(request));
            // 验证码正确，判断用户是否存在
            Admin admin = service.adminLogin(vo);
            if (admin != null) {
                // 用户名密码正确,将用户实体放入session中
                session.setAttribute("admin", admin); 
                msg = loginSuccess;
            } else {
                // 用户名密码不正确
                msg = accountOrPwdError;
            }
        } else {
            // 验证码不正确
            msg = codeError;
        }
        // 移除session中的验证码
        session.removeAttribute("loginCode");
        return msg;
    }
     
  
    /**
     * @Description (后台主页面所需图形表格数据)
     * @return
     * @throws Exception
     */
    @RequestMapping("/getSalesData")
    @ResponseBody
    public SalesDataMap getSalesData() throws Exception {
        SalesDataMap map = new SalesDataMap();
        //获取过去七天内，每天的交易总额
        List<SalesData> data = orderService.salesData();
        if(data != null && data.size() >= 1){
            map.addAsList(data);
        }
        //获取过去七天内销售各类型商品统计数据
        List<SalesCount> countData = orderService.getSalesCount();
        if(countData != null && countData.size() >1){
            map.addAsMap(countData, "option2");
        }
        //获取过去七天内各类商品成交金额，商品类型分组
        List<EchartsPojo> priceData = orderService.getSalesPriceCount();
        if(priceData != null && priceData.size() >1){
            map.addAsMap(priceData, "option3");
        }
        return map;
    }
    
    
    /**
     * @Description (异步响应未打印订单分页列表)
     * @return 分页所需的json信息
     */
    @RequestMapping("/getUnprintOrders")
    @ResponseBody
    public PageBean<OrderItem> getUnprintOrders(Integer currPage,Integer pageSize) {
        List<OrderItem> list = orderService.getOrdersList(currPage, pageSize, paid);
        Integer totalCount = orderService.getOrdersCount(paid);
        PageBean<OrderItem> pb = new PageBean<>(currPage, pageSize, list,totalCount);
        pb.setStatus(lauiTableStatus);
        return pb;
    }
    
    /**
     * @Description (异步响应未付款订单分页列表)
     * @return 分页所需的json信息
     */
    @RequestMapping("/getUnpaidOrders")
    @ResponseBody
    public PageBean<OrderItem> getUnpaidOrders(Integer currPage,Integer pageSize) {
        List<OrderItem> list = orderService.getOrdersList(currPage, pageSize, unpaid);
        Integer totalCount = orderService.getOrdersCount(unpaid);
        PageBean<OrderItem> pb = new PageBean<>(currPage, pageSize, list,totalCount);
        pb.setStatus(lauiTableStatus);
        return pb;
    }
    
    /**
     * @Description (异步响应未打印订单分页列表)
     * @return 分页所需的json信息
     */
    @RequestMapping("/getCompletedOrders")
    @ResponseBody
    public PageBean<OrderItem> getCompletedOrders(Integer currPage,Integer pageSize) {
        List<OrderItem> list = orderService.getOrdersList(currPage, pageSize, success);
        Integer totalCount = orderService.getOrdersCount(success);
        PageBean<OrderItem> pb = new PageBean<>(currPage, pageSize, list,totalCount);
        pb.setStatus(lauiTableStatus);
        return pb;
    }
    
    /**
     * 多条件分页查询订单
     */
    @RequestMapping("/searchOrders")
    @ResponseBody
    public PageBean<OrderItem> searchOrders(OrderQueryVo vo) {
        PageBean<OrderItem> pb = null;
        //判断是否是初始化
        if("0".equals(vo.getQueryStatus())) {
            pb = new PageBean<>();
            pb.setStatus(lauiTableStatus);
            pb.setCurrPage(1);
            pb.setPageSize(20);
            pb.setTotalCount(0);
            return pb;
        }
        pb =  orderService.getOrdersByCondition(vo);
        pb.setStatus(lauiTableStatus);
        return pb;
    }
    
    /**
     * 文件下载
     * @param id 订单id
     * @return 文件二进制流
     */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(Integer id)throws Exception {
       OrderItem oi = orderService.getOrderItem(id);
       HttpHeaders headers = new HttpHeaders();
       //下载显示的文件名，解决中文名称乱码问题  
       String downloadFielName = new String(oi.getFileName().getBytes("UTF-8"),"iso-8859-1");
       //通知浏览器以attachment（下载方式）打开图片
       headers.setContentDispositionFormData("attachment", downloadFielName); 
       //application/octet-stream ： 二进制流数据（最常见的文件下载）。
       headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
       return new ResponseEntity<>(Files.readAllBytes(Paths.get(oi.getFileAddr())), headers, HttpStatus.CREATED);
    }
    


    @RequestMapping("/complated")
    @ResponseBody
    /**
    * @Author:liujianxin
    * @Description:
    * @params:[id]
    * @return: java.lang.String
    * @Date: 2018/4/23 21:56
    */
    public String complatedOrder(Integer id) {
        //service
        orderService.updateOrderStatus(id,success);
        return "OK";
    }
}
